package com.example.gitpart03;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;

public class ProductAdapter extends BaseAdapter {
    private Context context;
    private List<Product> productList;

    public ProductAdapter(Context context, List<Product> productList) {
        this.context = context;
        this.productList = productList;
    }

    @Override
    public int getCount() {
        return productList.size();
    }

    @Override
    public Object getItem(int position) {
        return productList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.chanpin_list, parent, false);
            holder = new ViewHolder();
            holder.imgProduct = convertView.findViewById(R.id.yogurt_leixing_img);
            holder.txtName = convertView.findViewById(R.id.yogurt_leixing);
            holder.txtPrice = convertView.findViewById(R.id.price_num_begin);
            holder.txtPriceEnd = convertView.findViewById(R.id.price_end);
            holder.btnGuige = convertView.findViewById(R.id.btn_guige);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Product product = productList.get(position);
        holder.txtName.setText(product.getName());
        holder.txtPrice.setText(product.getPrice());
        holder.txtPriceEnd.setText(product.getPriceEnd());
        holder.imgProduct.setImageResource(product.getImageResId());

        // 设置按钮点击事件
        final int currentPosition = position;
        holder.btnGuige.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 创建一个 Intent 来启动显示 third_page 的 Activity
                Intent intent = new Intent(context,ThirdPage.class);
                // 可以传递产品信息到新页面
                intent.putExtra("productName", productList.get(currentPosition).getName());
                intent.putExtra("productPrice", productList.get(currentPosition).getPrice());
                intent.putExtra("productImageResId", productList.get(currentPosition).getImageResId());
                context.startActivity(intent);
            }
        });

        return convertView;
    }

    private static class ViewHolder {
        ImageView imgProduct;
        TextView txtName;
        TextView txtPrice;
        TextView txtPriceEnd;
        Button btnGuige;
    }
}